<style scoped>
    .layui-row {
        overflow: hidden;
    }
    .select-item {
        float: left;
        width: 100%;
        height: 50px;
        word-break:break-all;
    }
    .layui-row:after, .layui-row:before {
        clear: none;
    }
    .layui-form >>> .layui-form-select{
        z-index: inherit;
    }
    .department >>> .layui-table td, .layui-table th {
        padding: 9px 2px;
        white-space: nowrap;
    }

</style>

<template>
    <div class="department">
        <!--        <div style="height:50px">-->
        <!--&lt;!&ndash;            <a href="javascript:;" class="layui-btn" @click="add"><i class="layui-icon">&#xe654;</i>导出excel</a>&ndash;&gt;-->
        <!--        </div>-->
        <form class="layui-form " >

            <div  class="layui-col-lg4 select-item" >
                <label>查询条件: </label>
                <div class="layui-inline" style="width: 200px">
                    <input type="text" v-model="starttime" id="starttime" autocomplete="off" placeholder="请选择开始时间" class="layui-input key">
                </div>
                <div class="layui-inline" style="width: 200px">
                    <input type="text" v-model="endtime" id="endtime" autocomplete="off"  placeholder="请选择结束时间" class="layui-input key">
                </div>
                <div class="layui-input-inline" style="width: 200px">
                    <select class="layui-select" lay-verify="required" id="farmerid" lay-filter="farmers" style="width: 200px" lay-search>
                        <option value="">请选择所属种植户</option>
                    </select>
                </div>
                <div class="layui-inline" style="width: 200px" id="srguid" lay-filter="storeroom" >
                    <!--<select name="srguid"  id="srguid"  lay-filter="storeroom"       placeholder="请选择库房"   class="layui-form-select"   >
                        <option value="" >请选择库房</option>
                        <option v-for="item in storeroom" :value="item.guid" >{{item.name}}</option>


                    </select>-->
                </div>
                <div class="layui-inline" style="width: 200px">
                    <select  name="shguid"  id="shguid" placeholder="请选择库间"    class="layui-input layui-unselect"    >
                    </select>
                </div>
            </div>
            <div  class="layui-col-lg4 select-item" style="margin-left: 64px;">
                <div class="layui-inline" style="width: 200px">
                    <select name="type" id="type" lay-filter="type" class="layui-form-select">
                        <option value="">请选择产品类型</option>
                        <option v-for="item in types" :value="item.dictkey">{{item.dicttext}}</option>
                    </select>
                </div>
                <div class="layui-inline" style="width: 200px">
                    <select name="productid" id="productid" lay-filter="product" class="layui-form-select">
                        <option value="">请选择产品</option>
                        <option v-for="item in productinfo" :value="item.guid">{{item.productname}}</option>
                    </select>
                </div>
                <div class="layui-form layui-inline" lay-filter="specid" style="width: 200px">
                    <select name="specid" id="specid" class="layui-form-select">
                    </select>
                </div>
            </div>

            <div  class="layui-col-lg4 select-item" >
                <label>汇总条件: </label>
                <div class="layui-inline" style="width: 225px;height: auto">
                    <select   v-model="othercondition" name="othercondition"  id="othercondition" placeholder="请选择库房"   class="layui-form-select"   >
                        <option value="" selected >库房</option>
                        <option value="sh">库间</option>
                        <option value="product">产品</option>
                        <option value="sp">规格</option>
                    </select>
                </div>
                <div class="layui-inline" id="percheck">
                </div>
                <div class="layui-inline" style="width: 100px;">
                    <input type="checkbox" name="byday" id="byday" value="byday"  title="每日" >
                </div>
                <button type="button" class="layui-btn sou" @click="search">搜索</button>
                <button type="button" class="layui-btn sou" @click="exportExcel">导出excel</button>
            </div>

            <!--            <div  class="layui-col-lg4 select-item" style="text-align: right;" >-->

            <!--                <button type="button" class="layui-btn sou" @click="search">搜索</button>-->
            <!--                <button type="button" class="layui-btn sou" @click="exportExcel">导出excel</button>-->
            <!--            </div>-->

        </form>
        <div style="width: 100%;overflow: auto;margin-bottom: 10px;" id="textarea">
            <table class="layui-table layui-form" >
                <!--                -->
                <thead>
                <tr>
                    <th>库房 </th>
                    <th v-if="whinform[0] != undefined && (othercondition== 'sh' || othercondition== 'product' || othercondition== 'sp')  "  >库间 </th>
                    <th v-if="whinform[0] != undefined && whinform[0].companyname != '' && showCompany  "  >公司 </th>
                    <th v-if="whinform[0] != undefined && (othercondition== 'sp' || othercondition== 'product') "  >产品 </th>
                    <th v-if="whinform[0] != undefined && othercondition== 'sp' "  >规格 </th>

                    <th v-if="byday == ''">期初库存</th>
                    <th v-if="byday != ''">日期</th>
                    <th>采收入库</th>
                    <th>生产入库</th>
                    <th>调整入库</th>
                    <th>退料入库</th>
                    <th>调拨入库</th>
                    <th>领料出库</th>
                    <!--                <th>生产报废 </th>-->
                    <th>销售出库</th>
                    <th>调整出库</th>
                    <th>调拨出库</th>
                    <th>腐烂报废</th>
                    <th>库损报废</th>
                    <th>期末库存</th>
                    <th>库存单位</th>

                </tr>
                </thead>
                <tbody>

                <tr class="id9"  v-for="(row, i) in whinform" >
                    <td>{{row.srname}}</td>
                    <td v-if="whinform[0] != undefined && (othercondition== 'sh' || othercondition== 'product' || othercondition== 'sp') " >{{row.shname}}</td>
                    <td v-if="whinform[0] != undefined && whinform[0].companyname != '' && showCompany  " >{{row.companyname}}</td>
                    <td v-if="whinform[0] != undefined && (othercondition== 'sp' || othercondition== 'product') " >{{row.productname}}</td>
                    <td v-if="whinform[0] != undefined && othercondition== 'sp' " >{{row.specname}}</td>
                    <td v-if="byday == ''">{{row.startstore}}</td>
                    <td v-if="byday != ''">{{row.rptdate}}</td>
                    <td>{{row.buyinweightSUM}}</td>
                    <td>{{row.prodinweightSUM}}</td>
                    <td>{{row.adjinweightSUM}}</td>
                    <td>{{row.retinweightSUM}}</td>
                    <td>{{row.transinweightSUM}}</td>
                    <td>{{row.pickoutweightSUM}}</td>
                    <!--                    <td>{{row.pscrapweightSUM}}</td>-->
                    <td>{{row.selloutweightSUM}}</td>
                    <td>{{row.adjoutweightSUM}}</td>
                    <td>{{row.transoutweightSUM}}</td>
                    <td>{{row.scrbadoutweightSUM}}</td>
                    <td>{{row.scrlostoutweightSUM}}</td>
                    <td>{{row.endstore}}</td>
                    <td>{{row.stockunit}}</td>

                </tr>
                <tr v-if="whinform.length > 0">
                    <td>合计：</td>
                    <td v-if="whinform[0] != undefined && (othercondition== 'sh' || othercondition== 'product' || othercondition== 'sp') " ></td>
                    <td v-if="whinform[0] != undefined && whinform[0].companyname != '' && showCompany  " ></td>
                    <td v-if="whinform[0] != undefined && (othercondition== 'sp' || othercondition== 'product') " ></td>
                    <td v-if="whinform[0] != undefined && othercondition== 'sp' " ></td>
                    <td v-if="byday == ''">{{datasum.startstore}}</td>
                    <td v-if="byday != ''"></td>
                    <td>{{datasum.buyinweightSUM}}</td>
                    <td>{{datasum.prodinweightSUM}}</td>
                    <td>{{datasum.adjinweightSUM}}</td>
                    <td>{{datasum.retinweightSUM}}</td>
                    <td>{{datasum.transinweightSUM}}</td>
                    <td>{{datasum.pickoutweightSUM}}</td>
                    <!--                    <td>{{datasum.pscrapweightSUM}}</td>-->
                    <td>{{datasum.selloutweightSUM}}</td>
                    <td>{{datasum.adjoutweightSUM}}</td>
                    <td>{{datasum.transoutweightSUM}}</td>
                    <td>{{datasum.scrbadoutweightSUM}}</td>
                    <td>{{datasum.scrlostoutweightSUM}}</td>
                    <td>{{datasum.endstore}}</td>
                    <td>{{datasum.stockunit}}</td>
                </tr>
                </tbody>
            </table>

        </div>


    </div>
</template>

<script>
    import Pagination from '../common/Pagination.vue'
    export default {
        name: 'Exporywhinform',
        components: {Pagination},
        data () {
            return {
                departments: [],
                currentPage: 1,
                rows: 10,
                totalPage: 0,
                searchName: '',
                afterList: [],
                storehouseroom:[],
                storeroom:[],
                starttime:"",
                endtime:"",
                farmerid: '',
                farmers: [],
                specid: '',
                productid: '',
                type: '',
                srguid:"",
                shguid:"",
                datasum: {},
                whinform:[],
                exportpage:1,
                othercondition:"",
                byday: '',
                showCompany: false,
                organization: [],
                productinfo: [],
                types: [],
                sps: [],
            }
        },
        mounted() {
            let that = this;
            this.getBaseInfo();
            this.getRooms();
            this.loadEmnu();

            layui.use(['form'], function () {
                var form = layui.form,
                    layer = layui.layer;
                form.on('input(storeroom)', function(data){
                    console.log('data:', data)
                     $("#shguid").empty();
                    $('#shguid').append(new Option('请选择', ""));// 下拉菜单里添加元素。
                    $.each(that.storehouseroom, function (index, item) {
                        if(item.storeguid == data.value){
                            $('#shguid').append(new Option(item.name , item.guid));// 下拉菜单里添加元素。
                        }
                    });
                    layui.form.render("select");
                });
                form.on('select(product)', function(data){
                    that.getSps(data.value)
                });
            });
            this.starttime = this.getNowMonthDate();
            this.endtime = this.getDate();
            layui.use('laydate', function(){
                var laydate = layui.laydate;

                //执行一个laydate实例
                laydate.render({
                    elem: '#starttime', //指定元素
                    // value: that.getNowMonthDate()
                });
                //执行一个laydate实例
                laydate.render({
                    elem: '#endtime', //指定元素
                    // value: that.getDate(-1)
                });
            });
            // $('#percheck').append('<input type="checkbox" name="orgguidcondition" id="orgguidcondition" value="1"  title="公司" >');

            layui.form.render();
        },
        updated: function () {
            layui.form.render('select');
            layui.form.render();
        },
        methods: {
            getBaseInfo: function(type = '') {
                var that = this;
                $.ajax({
                    url: '/sales/Whoutform!getBaseInfo.action?openid=' + localStorage.openid,
                    type: "post",
                    data: {type: 2},
                    dataType: "json",
                    success: function(res) {
                        if (res.msg == 'success') {
                            let data =res;
                            that.storehouseroom = data.storehouseroom;
                            that.organization = data.organization;
                            that.productinfo = data.productinfo;
                            that.types = data.types;
                        } else {
                            $.toast("系统错误", 'forbidden');
                        }
                    },
                    complete: function () {
                        layer.close();
                    }
                });
            },
            getSps: function(productid) {
                this.axios({
                    method: 'get',
                    url: '/produce/Whinapply!getSpeByproduct.action',
                    params: {productid: productid}
                }).then((response) => {
                    if (response.data.msg == 'success') {
                        let data = response.data;
                        // this.sps = data.specifications;

                        $("#specid").empty();
                        $('#specid').append(new Option('请选择', ""));// 下拉菜单里添加元素。
                        $.each(data.specifications, function (index, item) {
                            $('#specid').append(new Option(item.name , item.guid));// 下拉菜单里添加元素。
                        });
                        layui.form.render("select", 'specid');
                    } else {
                        this.toastError("获取规格数据失败");
                    }

                })
            },
            //获取当前日期
            getDate: function (dayCount = 0) {
                var dd = new Date();
                dd.setDate(dd.getDate()+dayCount);//设置日期
                var y = dd.getFullYear();
                var m = dd.getMonth()+1;//获取当前月份的日期
                var fullM = m.length == 2 ? m : '0' + m;
                var d = dd.getDate();
                return y+"-"+fullM+"-"+d;
            },
            //获取本月第一天
            getNowMonthDate: function () {
                var date = new Date();
                var year = date.getFullYear() + "";
                var month = (date.getMonth() + 1) + "";
                // 本月第一天日期
                var begin = year + "-" + month + "-01"
                return begin;
            },
            // 数据转换
            tansList () {
                this.afterList = Object.values(this.whinform.reduce((temp, item) => {
                    if( temp[item.code] ) {
                        temp[item.code].push(item)
                    }else {
                        temp[item.code]  = [item]
                    }
                    return temp
                },{}))
            },
            countRowspan:function (data){
                var count = 0;
                $.each( this.whinform, function( key, item ) {
                    console.log(item.code + " == " + data.code);
                    if( data.code == item.code){
                        count = count + 1;
                    }
                } );
                return count;
            },
            search: function() {
                this.getPageData('search');
            },
            turnPage: function(data){
                this.currentPage = data;
                this.exportpage = data
                this.getPageData();
            },

            getPageData: function(type = '') {
                if (this.dateToValue($('#endtime').val()) < this.dateToValue($('#starttime').val())) {
                    this.toastText('结束时间须大于起始时间！');
                    return;
                }
                var that = this;

                let loader = layui.layer.load();

                let postData = {pageSize: that.rows ,pageNo:this.exportpage};
                if (type != 'search') {
                    postData.page = that.currentPage;
                }
                that.starttime = $('#starttime').val();
                that.endtime = $('#endtime').val();
                that.farmerid = $("#farmerid").val();
                that.productid =  $('#productid').val();
                that.type = $('#type').val();
                that.specid =  $('#specid').val();
                that.srguid = $("input[name='srguid']").val();
                that.shguid =  $('#shguid').val();
                that.othercondition =  $('#othercondition').val();
                that.showCompany =  $('#orgguidcondition').is(':checked');
                that.byday =  $('#byday').is(':checked') ? $('#byday').val() : '';

                //that.orgguidcondition =  $('#orgguidcondition').val();

                // if(that.starttime == '' || that.endtime  == ''){
                //     that.alert("请选择开始时间以及结束时间！");
                //     layer.close(loader);
                //     return;
                // }

                var orgSelect = $('#orgguidcondition').is(':checked');
                if(orgSelect){
                    postData.orgguidcondition = "company";
                }
                postData.byday = that.byday;
                postData.othercondition = that.othercondition;
                postData.starttime = that.starttime;
                postData.endtime = that.endtime;
                postData.farmerid = that.farmerid;
                postData.productid = that.productid;
                postData.type = that.type;
                postData.specid = that.specid;
                postData.srguid = that.srguid;
                postData.shguid = that.shguid;
                postData.srtype = 2;
                var srguids = [];
                if(postData.srguid == ""){
                    $.each(that.storeroom, function (index, itemroom) {
                        srguids.push(itemroom.guid)
                    });
                    postData.srguidStr = srguids.toString();
                }
                $.ajax({
                    url: '/repository/RptStoreanalysis!list.action',
                    type: "post",
                    data: postData,
                    dataType: "json",
                    success: function(res) {
                        if (res.result == 'success') {
                            that.datasum = res.datasum;
                            //分页数据赋值
                            // that.currentPage = res.data.pageNo;
                            // that.totalPage = res.data.pageCount;
                            that.whinform = res.data.filter(item => {
                                return item.startstore != '' || item.buyinweightSUM != '' || item.prodinweightSUM != '' || item.adjinweightSUM != '' || item.retinweightSUM != '' || item.transinweightSUM != '' || item.pickoutweightSUM != '' || item.selloutweightSUM != '' || item.adjoutweightSUM != '' || item.transoutweightSUM != '' || item.scrbadoutweightSUM != '' || item.scrlostoutweightSUM != '' || item.endstore != '';
                            });
                            that.tansList()
                        } else if (res.result == 'false') {
                            that.alert(res.data);
                        } else {
                            that.alert("系统错误");
                        }
                    },
                    complete: function () {
                        layer.close(loader);
                        $('#textarea').css('max-height', $(window).height() - $('#textarea').offset().top - 10)
                    }
                });
            },
            initSrSelect: function () {
                let that = this;
                layui.xmSelect.render({
                    el: '#srguid',
                    tips: '请选择库房',
                    name: 'srguid',
                    prop: {
                        name: 'name',
                        value: 'guid'
                    },
                    data: this.storeroom,
                    on: function(data) {
                        let selectdRooms = data.arr.map(item => {
                            return item.guid;
                        });

                        $("#shguid").empty();
                        $('#shguid').append(new Option('请选择', ""));// 下拉菜单里添加元素。
                        if (data.arr.length == 1) {
                            $.each(that.storehouseroom, function (index, item) {
                                if(selectdRooms.indexOf(item.storeguid) > -1){
                                    $('#shguid').append(new Option(item.name , item.guid));// 下拉菜单里添加元素。
                                }
                            });
                        }
                        layui.form.render("select");
                    }
                })
            },
            loadEmnu: function () {
                let that = this;
                let postParam = {};
                postParam['entity.userType'] = 2;
                this.axios({
                    method: 'get',
                    url: '/system/Tuser!getUserAll.action',
                    params: postParam
                }).then(response => {
                    if (response.data.info != undefined && response.data.info.length > 0) {
                        that.farmers = response.data.info;
                        $.each(response.data.info, function (index, item) {
                            console.log(item)
                            $('#farmerid').append("<option   value=" + item.guid + " > " + item.realname + "</option>"); // 下拉菜单里添加元素
                        });
                        layui.form.render("select");
                    }  else {
                        this.toastText('获取负责人数据失败');
                    }
                });
            },
            getRooms: function() {
                let postData = {functionTypes: 10, orgguids: $('#farmerid').val(),type: 2};
                let that = this;
                $.ajax({
                    url: '/sales/Salespermission!getPermisForStore.action',
                    type: "post",
                    data: postData,
                    dataType: "json",
                    success: function(res) {
                        if (res.msg == 'true') {
                            that.storeroom = res.storeroom;
                            that.initSrSelect();
                        } else {
                            that.toast('获取库房数据失败！');
                        }
                    }
                });

            },
            compare: function (property){
                return function(a,b){
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                }
            },
            add: function () {
                this.$parent.switchPage('addSalesPermission');
            },
            exportExcel:function (){
                var that = this;
                let postData = {pageSize: that.rows ,pageNo:this.exportpage};
                that.starttime = $('#starttime').val();
                that.endtime = $('#endtime').val();
                that.farmerid =  $('#farmerid').val();
                that.productid =  $('#productid').val();
                that.specid =  $('#specid').val();
                that.srguid =  $('#srguid').val();
                that.shguid =  $('#shguid').val();                that.othercondition =  $('#othercondition').val();
                that.byday =  $('#byday').is(':checked') ? $('#byday').val() : '';

                var orgSelect = $('#orgguidcondition').is(':checked');
                if(orgSelect){
                    postData.orgguidcondition = "company";
                }
                postData.othercondition = that.othercondition;
                postData.starttime = that.starttime;
                postData.endtime = that.endtime;
                postData.farmerid = that.farmerid;
                postData.productid = that.productid;
                postData.specid = that.specid;
                postData.srguid = that.srguid;
                postData.shguid = that.shguid;
                postData.byday = that.byday;

                window.location.href="/repository/RptStoreanalysis!exportOrderData.action?starttime=" + that.starttime + "&endtime=" + that.endtime + "&srguid=" + that.srguid   + "&othercondition=" + that.othercondition +  "&byday=" +  postData.byday
            },
            edit: function (id) {
                this.$parent.gid = id;
                this.$parent.switchPage('EditDepartment');
            },
            del: function (id) {
                let that = this;
                layer.confirm('确定要删除该数据吗？', function () {
                    let loader = layer.load();
                    $.ajax({
                        url: '/sales/Salespermission!del.action',
                        type: "post",
                        data: {guid: id},
                        dataType: "json",
                        success: function(res) {
                            if (res.info == "ok") {
                                that.toast("删除成功");
                                that.getPageData('search');
                            } else {
                                that.toast("系统错误");
                            }
                        },
                        complete: function () {
                            layer.close(loader);
                        }
                    });
                })
            }
        }
    }
</script>
